//
//  MHMomentViewController.m
// MiaoCircle
//
//Created by acgera on 2018/4/9.
//  Copyright © 2018年 acgera. All rights reserved.
//

#import "MHMomentViewController.h"
#import "MHMomentHeaderView.h"
#import "MHMomentFooterView.h"
#import "MHMomentCommentCell.h"
#import "MHMomentAttitudesCell.h"
#import "MHMomentProfileView.h"
#import "MHMomentOperationMoreView.h"
#import "LCActionSheet.h"
#import "MHEmoticonManager.h"
#import "MHMomentHelper.h"
#import "MHMomentCommentToolView.h"
#import "ARSegmentControllerDelegate.h"
#import "MHViewController+MHCommonAlert.h"
#import "MHshareRecent.h"
#import "MHAlertMessageView.h"

@interface MHMomentViewController ()<ARSegmentControllerDelegate>
/// viewModel
@property (nonatomic, readonly, strong) MHMomentViewModel *viewModel;
/// tableHeaderView
@property (nonatomic, readwrite, weak) MHMomentProfileView *tableHeaderView;
/// commentToolView
@property (nonatomic, readwrite, weak) MHMomentCommentToolView *commentToolView;
/// 选中的索引 selectedIndexPath
@property (nonatomic, readwrite, strong) NSIndexPath * selectedIndexPath;
/// 记录键盘高度
@property (nonatomic, readwrite, assign) CGFloat keyboardHeight;

@property(nonatomic, assign) BOOL inThisPage;
@end

@implementation MHMomentViewController
@dynamic viewModel;

- (void)dealloc{
    MHDealloc;
}

- (void)viewDidLoad {
    [super viewDidLoad];
    
    // 初始化子控件
    [self _setupSubViews];
        /// 初始化导航栏Item
//    [self _setupNavigationItem];
    @weakify(self);
    [[MHNotificationCenter rac_addObserverForName:MHReloadMomentPageDataNotification object:nil] subscribeNext:^(id x) {
        @strongify(self);
        [self.viewModel.requestRemoteDataCommand execute:@1];
    }];
    
//    self.tableView.estimatedRowHeight =0;
//    self.tableView.estimatedSectionHeaderHeight =0;
//    self.tableView.estimatedSectionFooterHeight =0;    
//    [[MHNotificationCenter rac_addObserverForName:MHReloadMomentSecondPageDataNotification object:nil] subscribeNext:^(id x) {
//        @strongify(self);
//        [self.viewModel.requestRemoteDataCommand execute:@1];
//    }];
    
}

-(void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];
    self.inThisPage  = YES;
}

-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [MHMomentHelper hideAllPopViewWithAnimated:NO];
    self.inThisPage  = false;
}
//-(void)viewDidDisappear:(BOOL)animated
//{
//
//}


#pragma mark - Override

-(NSString *)segmentTitle
{
    return  self.viewModel.title;
}

-(UIScrollView *)streachScrollView
{
    return self.tableView;
}

- (void)bindViewModel{
    [super bindViewModel];
    
    /// ... 事件处理...
    /// 全文/收起
    @weakify(self);
    [[self.viewModel.reloadSectionSubject deliverOnMainThread] subscribeNext:^(NSNumber * section) {
        @strongify(self);
        /// 局部刷新 (内部已更新子控件的尺寸，这里只做刷新)
        /// 这个刷新会有个奇怪的动画
//        [UIView performWithoutAnimation:^{
//            [self.tableView reloadData];
        //          }];
        [UIView performWithoutAnimation:^{
          
            [self.tableView reloadSection:section.integerValue withRowAnimation:UITableViewRowAnimationNone];
        }];
    }];
    
    /// 评论
    [[self.viewModel.commentSubject deliverOnMainThread] subscribeNext:^(NSNumber * section) {
        @strongify(self);
        /// 记录选中的Section 这里设置Row为-1 以此来做判断
        NSIndexPath *indexPath = [NSIndexPath indexPathForRow:-1 inSection:section.integerValue];
        /// 显示评论
        [self _commentOrReplyWithItemViewModel:self.viewModel.dataSource[section.integerValue] indexPath:indexPath];
    }];
    
    /// 点击手机号码
//    [[self.viewModel.phoneSubject deliverOnMainThread] subscribeNext:^(NSString * phoneNum) {
//        @strongify(self);
//        LCActionSheet *sheet = [LCActionSheet sheetWithTitle:[NSString stringWithFormat:@"%@可能是一个电话号码，你可以",phoneNum] cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
//            if (buttonIndex == 0) return ;
//        } otherButtonTitles:@"呼叫",@"复制号码",@"添加到手机通讯录", nil];
//        [sheet show];
        
//    }];
    
    
    
    /// 监听键盘 高度
    /// 监听按钮
    [[[[[NSNotificationCenter defaultCenter] rac_addObserverForName:UIKeyboardWillChangeFrameNotification object:nil] takeUntil:self.rac_willDeallocSignal ]
      deliverOnMainThread]
     subscribeNext:^(NSNotification * notification) {
         @strongify(self);
         @weakify(self);
         [self mh_convertNotification:notification completion:^(CGFloat duration, UIViewAnimationOptions options, CGFloat keyboardH) {
             @strongify(self);
             
             //只在当前页面执行这个逻辑
             if (!self.inThisPage) {
                 return;
             }

             if (keyboardH <= 0) {
                 keyboardH = -1 * self.commentToolView.mh_height;
             }
             self.keyboardHeight = keyboardH;
             /// 全局记录keyboardH
             AXAppDelegate.sharedDelegate.showKeyboard = (keyboardH > 0);
             // bottomToolBar距离底部的高
             [self.commentToolView mas_updateConstraints:^(MASConstraintMaker *make) {
    
#warning 特殊处理 commentToolView；
                 //特殊处理最近的
                 if (self.viewModel.isRecent || self.viewModel.isFootPrint || self.viewModel.isAskList || self.viewModel.isAnserList) {
                     make.bottom.equalTo(self.view).with.offset(-1 *keyboardH);
                 }else
                 {
                     make.bottom.equalTo(self.view).with.offset(-1 *keyboardH);
                 }
                 
             }];
             // 执行动画
             [UIView animateWithDuration:duration delay:0.0f options:options animations:^{
                 // 如果是Masonry或者autoLayout UITextField或者UITextView 布局 必须layoutSubviews，否则文字会跳动
                 [self.view layoutSubviews];
                 /// 滚动表格
                 [self _scrollTheTableViewForComment];
             } completion:nil];
         }];
     }];
    
    
    //// 监听commentToolView的高度变化
    [[RACObserve(self.commentToolView, toHeight) distinctUntilChanged] subscribeNext:^(NSNumber * toHeight) {
        @strongify(self);
        if (toHeight.floatValue < MHMomentCommentToolViewMinHeight) return ;
        /// 更新CommentView的高度
        [self.commentToolView mas_updateConstraints:^(MASConstraintMaker *make) {
            make.height.mas_equalTo(toHeight);
        }];
        [UIView animateWithDuration:.25f animations:^{
            // 适当时候更新布局
            [self.view layoutSubviews];
            /// 滚动表格
            [self _scrollTheTableViewForComment];
        }];
    }];
    
}
- (UITableViewCell *)tableView:(UITableView *)tableView dequeueReusableCellWithIdentifier:(NSString *)identifier forIndexPath:(NSIndexPath *)indexPath{
    return [MHMomentContentCell cellWithTableView:tableView];
}

- (void)configureCell:(MHMomentContentCell *)cell atIndexPath:(NSIndexPath *)indexPath withObject:(id)object{
    MHMomentItemViewModel *itemViewModel =  self.viewModel.dataSource[indexPath.section];
    id model = itemViewModel.dataSource[indexPath.row];
    [cell bindViewModel:model];
}

#pragma mark - 初始化子控件
- (void)_setupSubViews{
    /// 配置tableView
    self.tableView.backgroundColor = [UIColor whiteColor];
    /// 固定高度-这样写比使用代理性能好，且使用代理会获取每次刷新数据会调用两次代理 ，苹果的bug
    self.tableView.sectionFooterHeight =  MHMomentFooterViewHeight;
    
    /// 个人信息view
//    if (self.viewModel.isRecent) {
//        MHMomentProfileView *tableHeaderView = [[MHMomentProfileView alloc] init];
//        [tableHeaderView bindViewModel:self.viewModel.profileViewModel];
//        self.tableHeaderView = tableHeaderView;
//        
//        @weakify(self);
//        /// 动态更新tableHeaderView的高度. PS:单纯的设置其高度无效的
//        [[RACObserve(self.viewModel.profileViewModel, unread)
//          distinctUntilChanged]
//         subscribeNext:^(NSNumber * unread) {
//             @strongify(self);
//             tableHeaderView.mh_height = self.viewModel.profileViewModel.height;
//             [self.tableView beginUpdates];  // 过度动画
//             self.tableView.tableHeaderView = tableHeaderView;
//             [self.tableView endUpdates];
//         }];
//    }

    
    /// 这里设置下拉黑色的背景图
    UIImageView *backgroundView = [[UIImageView alloc] initWithFrame:MH_SCREEN_BOUNDS];
    backgroundView.mh_size = MH_SCREEN_BOUNDS.size;
    backgroundView.image = MHImageNamed(@"wx_around-friends_bg_320x568");
    backgroundView.mh_y = -backgroundView.mh_height;
    [self.tableView addSubview:backgroundView];
    
    
    /// 添加评论View
    MHMomentCommentToolView *commentToolView = [[MHMomentCommentToolView alloc] init];
    self.commentToolView = commentToolView;
    [self.view addSubview:commentToolView];
    
    [commentToolView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.left.and.right.equalTo(self.view);
        make.height.mas_equalTo(60);
        make.bottom.equalTo(self.view).with.offset(isIPhoneX()? 60 + zh_safeAreaHeight() + 25 : 60 );
//         make.bottom.equalTo(self.view).with.offset(60 + zh_safeAreaHeight());//在底部看不见的位置
//        make.bottom.equalTo(self.view);
    }];
}


/// PS:这里复写了 MHTableViewController 里面的UITableViewDelegate和UITableViewDataSource的方法，所以大家不需要过多关注 MHTableViewController的里面的UITableViewDataSource方法
#pragma mark - UITableViewDataSource & UITableViewDelegate
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return self.viewModel.dataSource.count;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    MHMomentItemViewModel *itemViewModel =  self.viewModel.dataSource[section];
    return itemViewModel.dataSource.count;
}

// custom view for header. will be adjusted to default or specified header height
- (nullable UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    MHMomentHeaderView *headerView = [MHMomentHeaderView headerViewWithTableView:tableView];
    /// 传递section 后期需要用到
    headerView.section = section;
    MHMomentItemViewModel *itemViweModel = self.viewModel.dataSource[section];
    [headerView bindViewModel:self.viewModel.dataSource[section]];
    @weakify(self)
    
    //分享
    [itemViweModel.shareMomentCommand.executionSignals.switchToLatest subscribeNext:^(MHshareRecent *shareModel) {
        @strongify(self);
        self.zh_popupController = [zhPopupController new];
        self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
        zhWallView *wallView =  [self wallView];
        wallView.section = (int) section;
        shareModel.shareMoment = itemViweModel.moment;
        wallView.models = [self shareWallModelsWithSection:wallView.section shareModel:shareModel];
        [wallView autoAdjustFitHeight];
        @weakify(self);
        wallView.didClickFooter = ^(zhWallView * _Nonnull sheetView) {
            @strongify(self);
            [self.zh_popupController dismiss];
        };
        [self.zh_popupController presentContentView:wallView];
    }];
//    [[itemViweModel.shareMomentCommand executionSignals] subscribeNext:^(MHshareRecent *shareModel) {
//
//
//    }];
    
    [[itemViweModel.showBottomMenuViewCommand executionSignals] subscribeNext:^(id x) {
        @strongify(self);
        self.zh_popupController = [zhPopupController new];
        self.zh_popupController.layoutType = zhPopupLayoutTypeBottom;
        zhWallView *wallView =  [self wallView];
        wallView.section = (int) section;
        wallView.models = [self wallModelsWithSection:wallView.section itemViweModel:itemViweModel];
        [wallView autoAdjustFitHeight];
        @weakify(self);
        wallView.didClickFooter = ^(zhWallView * _Nonnull sheetView) {
            @strongify(self);
            [self.zh_popupController dismiss];
        };
        [self.zh_popupController presentContentView:wallView];
        
    }];
    
    return headerView;
}


- (NSArray *)shareWallModelsWithSection:(int )seciton shareModel:(MHshareRecent *)recent{
    

    __weak __typeof(self)weakSelf = self;
    VoidBlock_id_int shareFriend =  ^(UIButton *button, int index) {
        
        [weakSelf.zh_popupController dismiss];
      [MHMomentHelper shareWithSharRecent:recent shareType:MHCirclShareTypeWeChat];
        
    };
    
    VoidBlock_id_int shareTimeLine =  ^(UIButton *button, int index) {
        [weakSelf.zh_popupController dismiss];
       [MHMomentHelper shareWithSharRecent:recent shareType:MHCirclShareTypeWeChatTimeLine];
    };
    NSArray *arr1;
    if (recent.shareMoment.shareTimeLine) {
        arr1 = @[
     
                 @{titleKey   : @"微信朋友圈",
                   imgNameKey : @"icon_share_timeline",
                   excutesCustomBlock: shareTimeLine,
                   
                   },
                 ];
    }else
    {
        arr1 = @[
                 
                 @{titleKey   : @"微信",
                   imgNameKey : @"icon_share_wechat",
                   excutesCustomBlock: shareFriend,
                   
                   },
                 
                 @{titleKey   : @"微信朋友圈",
                   imgNameKey : @"icon_share_timeline",
                   excutesCustomBlock: shareTimeLine,
                   
                   },
                 ];
    }
    
   
    
    
    NSMutableArray *array1 = [NSMutableArray array];
    for (NSDictionary *dict in arr1) {
        NSString *text = [dict objectForKey:titleKey];
        NSString *imgName = [dict objectForKey:imgNameKey];
        NSString *seleImage = [dict objectForKey:selImageName];
        VoidBlock_id_int excutBlock = [dict objectForKey:excutesCustomBlock];
        BOOL isSeleted = [[dict objectForKey:modelSelected] boolValue];
        int index =  [arr1 indexOfObject:dict];
        [array1 addObject:[zhWallItemModel  modelWithImage:[UIImage imageNamed:imgName] selectImage:[UIImage imageNamed:seleImage] isSelect:isSeleted text:text clickBlock:excutBlock]];
    }
    
    return [NSMutableArray arrayWithObjects:array1, nil];
}


-(void)rightButtonClick
{
    if (self.viewModel.isFootPrint) {
        [self.viewModel.pushToChatView execute:self.viewModel.imUser];
    }
}

- (NSArray *)wallModelsWithSection:(int )seciton itemViweModel:(MHMomentItemViewModel * )itemViweModel{
    BOOL isTop = itemViweModel.moment.isTop;
    BOOL isEssence = itemViweModel.moment.isEssence;
    BOOL isCollection = itemViweModel.moment.isHaveCollect;
    __weak __typeof(self)weakSelf = self;
    VoidBlock_id_int top =  ^(UIButton *button, int index) {
        
        if (isTop) {
            [[weakSelf.viewModel.cancelTopMomentCommand execute:@(seciton)] subscribeNext:^(id x) {
                itemViweModel.moment.isTop = false;
//                [self.viewModel reloadSectionSubject];
            }];
        }else
        {
            [[weakSelf.viewModel.topMomentCommand execute:@(seciton)] subscribeNext:^(id x) {
                itemViweModel.moment.isTop = YES;
//                [self.viewModel reloadSectionSubject];
            }];
        }
        
        [weakSelf.zh_popupController dismiss];
    };
    
    VoidBlock_id_int collection =  ^(UIButton *button, int index) {
        @weakify(self);
        [[itemViweModel.collectionCommand execute: @{@"isCollection":@(isCollection),@"section":@(seciton)}] subscribeNext:^(id x) { 
        @strongify(self);
            itemViweModel.moment.isHaveCollect = !isCollection;
//                   int  index  =  [input intValue];
            //        MHMomentItemViewModel *momentItemViewModel = self.dataSource[index];


        }];
        [weakSelf.zh_popupController dismiss];
    };
    
    VoidBlock_id_int repo =  ^(UIButton *button, int index) {
        [weakSelf.viewModel.repoCommand execute:@(seciton)];
        [weakSelf.zh_popupController dismiss];
    };
    
    VoidBlock_id_int delete =  ^(UIButton *button, int index) {
        [self showAlertViewControllerWithTitle:@"删除该主题？" content:@"该主题删除后将不会显示在主题列表" comfirmblock:^{
            [weakSelf.viewModel.delMomentCommand execute:@(seciton)];
            [weakSelf.zh_popupController dismiss];
        } dissMissBlock:^{
            [weakSelf.zh_popupController dismiss];
        }];

    };
    VoidBlock_id_int essence =  ^(UIButton *button, int index) {
        if (isEssence) {
            
            [weakSelf.viewModel.cancelEssenceMomentCommand execute:@(seciton)];
        }else
        {
            [weakSelf.viewModel.setEssenceMomentCommand execute:@(seciton)];
        }
        [weakSelf.zh_popupController dismiss];
    };
   NSDictionary *topDic =   @{titleKey   : isTop ? @"取消置顶" : @"置顶",
      imgNameKey : @"cirle_more_topnor",
      selImageName:@"circle_more_topsel",
      modelSelected: @(isTop),
      excutesCustomBlock: top,
                              };
    
     NSDictionary *essenceDic =  @{titleKey   : isEssence ? @"取消精华":@"精华",
      imgNameKey : @"circle_more_jhnor",
      selImageName:@"circle_more_jhsel",
      modelSelected: @(isEssence),
      excutesCustomBlock: essence,
                                   };
    
     NSDictionary *repoDic =  @{titleKey   : @"举报",
      imgNameKey : @"circle_repo_normal",
      excutesCustomBlock: repo,
                                   };
    
   NSDictionary *delDic =   @{titleKey   : @"删除",
        imgNameKey : @"circle_more_del",
        excutesCustomBlock: delete,
                                };
    
    NSDictionary *collecitonDic =   @{titleKey   : isCollection ? @"取消收藏" : @"收藏",
                               imgNameKey : @"circle_collectionnor",
                               selImageName:@"circle_collectionsel",
                               modelSelected: @(isCollection),
                               excutesCustomBlock: collection,
                               };
                              
    MHMomentMemberIdentity identity = MHMemberIdentity([AXAppDelegate sharedDelegate].currentCircleInfo.ownerUid, itemViweModel.moment.publishUserId, [MHHTTPService sharedInstance].currentUser.userId);
    
//    MHCircleIdentityType identity = itemViweModel.moment.identType;

//    BOOL isOwner =  [[AXAppDelegate sharedDelegate].currentCircleInfo currentUserIsOwner];
    
    NSArray *arr1 = @[];
    NSArray *arr2 = @[];
    
    if (self.viewModel.isTheme) {
        if (identity == MHMomentOwnerToSelf) {
            arr1 =  @[topDic, essenceDic,collecitonDic,delDic];
            //        arr2 = @[];
        }else if(identity == MHMomentOwnerToMember)
        {
            arr1 =  @[topDic, essenceDic,collecitonDic,repoDic];
            arr2 = @[delDic];
        }else if(identity == MHMomentMemberToSelf)
        {
            arr1 =  @[];
            arr2 = @[collecitonDic,delDic];
        }else{
            arr2 = @[collecitonDic,repoDic];
        }
    }else
    {
        if (itemViweModel.moment.publishUserId == [MHHTTPService sharedInstance].currentUser.userId) {
              arr1 = @[collecitonDic,repoDic,delDic];
        }else
        {
            arr1 = @[collecitonDic,repoDic];
        }
      
    }
    
    

    NSMutableArray *array1 = [NSMutableArray array];
    for (NSDictionary *dict in arr1) {
        NSString *text = [dict objectForKey:titleKey];
        NSString *imgName = [dict objectForKey:imgNameKey];
        NSString *seleImage = [dict objectForKey:selImageName];
        BOOL isSeleted = [[dict objectForKey:modelSelected] boolValue];
        VoidBlock_id_int excutBlock = [dict objectForKey:excutesCustomBlock];
        int index =  [arr1 indexOfObject:dict];
        [array1 addObject:[zhWallItemModel  modelWithImage:[UIImage imageNamed:imgName] selectImage:[UIImage imageNamed:seleImage] isSelect:isSeleted text:text clickBlock:excutBlock]];
    }
    NSMutableArray *array2 = [NSMutableArray array];
    for (NSDictionary *dict in arr2) {
        NSString *text = [dict objectForKey:titleKey];
        NSString *imgName = [dict objectForKey:imgNameKey];
        NSString *seleImage = [dict objectForKey:selImageName];
        int index =  [arr2 indexOfObject:dict];
        VoidBlock_id_int excutBlock = [dict objectForKey:excutesCustomBlock];
        BOOL isSeleted = [[dict objectForKey:modelSelected] boolValue];
        [array2 addObject:[zhWallItemModel  modelWithImage:[UIImage imageNamed:imgName] selectImage:[UIImage imageNamed:seleImage] isSelect:isSeleted text:text clickBlock:excutBlock]];
    }
    NSMutableArray *resultArray = [NSMutableArray array];
    
    if (array1.count) {
        [resultArray appendObject:array1];
    }
    if (array2.count) {
        [resultArray appendObject:array2];
    }
    
    return resultArray;
}


// custom view for footer. will be adjusted to default or specified footer height
- (nullable UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section{
    return [MHMomentFooterView footerViewWithTableView:tableView];
}

/// 点击Cell的事件
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    
    if (self.viewModel.isDetail) {
        NSInteger section = indexPath.section;
        NSInteger row = indexPath.row;
        /// 先取出该section的说说
        MHMomentItemViewModel *itemViweModel = self.viewModel.dataSource[section];
        /// 然后取出该 row 的评论Or点赞
        MHMomentContentItemViewModel *contentItemViewModel = itemViweModel.dataSource[row];
        /// 去掉点赞
        if ([contentItemViewModel isKindOfClass:MHMomentAttitudesItemViewModel.class]) {
            [self.commentToolView mh_resignFirstResponder];
            return;
        }
        
        /// 判断是否是自己的评论  或者 回复
        MHMomentCommentItemViewModel *commentItemViewModel = (MHMomentCommentItemViewModel *)contentItemViewModel;
        if (commentItemViewModel.comment.fromUser.userId == self.viewModel.services.client.currentUser.userId) {
            /// 关掉键盘
            [self.commentToolView  mh_resignFirstResponder];
            
            /// 自己评论的活回复他人
            @weakify(self);
            LCActionSheet *sheet = [LCActionSheet sheetWithTitle:nil cancelButtonTitle:@"取消" clicked:^(LCActionSheet * _Nonnull actionSheet, NSInteger buttonIndex) {
                if (buttonIndex == 0) return ;
                @strongify(self);
                /// 删除数据源
                [self.viewModel.delCommentCommand execute:indexPath];
                
            } otherButtonTitles:@"删除", nil];
            NSIndexSet *indexSet = [NSIndexSet indexSetWithIndex:1];
            sheet.destructiveButtonIndexSet = indexSet;
            [sheet show];
            return;
        }
        
        MHLogFunc;
        /// 键盘已经显示 你就先关掉键盘
        if (MHSharedAppDelegate.isShowKeyboard) {
            [self.commentToolView mh_resignFirstResponder];
            return;
        }
        /// 评论
        [self _commentOrReplyWithItemViewModel:contentItemViewModel indexPath:indexPath];
    }else
    {
        [self.viewModel.didSelectCommand execute:@(indexPath.section)];
    }
    
    
}


// custom view for cell
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UITableViewCell *cell = [self tableView:tableView dequeueReusableCellWithIdentifier:@"UITableViewCell" forIndexPath:indexPath];
    // fetch object 报错 why???
    //    id object  = [self.viewModel.dataSource[indexPath.section] dataSource][indexPath.row];
    MHMomentItemViewModel *itemViewModel = self.viewModel.dataSource[indexPath.section];
    id object = itemViewModel.dataSource[indexPath.row];
    /// bind model
    [self configureCell:cell atIndexPath:indexPath withObject:(id)object];
    [self preloadDataWithCurrentIndex:self.viewModel.shouldMultiSections ? indexPath.section : indexPath.row];
    return cell;
}

/// 设置高度
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    MHMomentItemViewModel *itemViewModel = self.viewModel.dataSource[section];
    /// 这里每次刷新都会走两次！！！ Why？？？
    return itemViewModel.height;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    MHMomentItemViewModel *itemViewModel =  self.viewModel.dataSource[indexPath.section];
    /// 这里用 id 去指向（但是一定要确保取出来的模型有 `cellHeight` 属性 ，否则crash）
    id model = itemViewModel.dataSource[indexPath.row];
    return [model cellHeight];
}

-(CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section
{
    return 8;
}

/// 监听滚动到顶部
- (void)scrollViewDidScrollToTop:(UIScrollView *)scrollView{
    /// 这里下拉刷新
}

- (void)scrollViewWillBeginDragging:(UIScrollView *)scrollView{
    /// 处理popView
    [MHMomentHelper hideAllPopViewWithAnimated:NO];
}

#pragma mark - 辅助方法
- (void)_commentOrReplyWithItemViewModel:(id)itemViewModel indexPath:(NSIndexPath *)indexPath{
    /// 传递数据 (生成 replyItemViewModel)
    MHMomentReplyItemViewModel *viewModel = [[MHMomentReplyItemViewModel alloc] initWithItemViewModel:itemViewModel];
    viewModel.section = indexPath.section;
    viewModel.commentCommand = self.viewModel.commentCommand;
    self.selectedIndexPath = indexPath; /// 记录indexPath
    [self.commentToolView bindViewModel:viewModel];
    /// 键盘弹起
    [self.commentToolView  mh_becomeFirstResponder];
}

- (CGFloat)verticalOffsetForEmptyDataSet:(UIScrollView *)scrollView{
  
//    NSLog(@"self.tableView.tableHeaderView.frame.size.height = %f",self.tableView.tableHeaderView.frame.size.height);
    if (self.viewModel.isTheme) {

        UIView *emptyDataSetView = [self.tableView.subviews.rac_sequence objectPassingTest:^(UIView *view) {
            return [NSStringFromClass(view.class) isEqualToString:@"DZNEmptyDataSetView"];
        }];
        CGFloat inset = emptyDataSetView.frame.origin.y < - 64 ? (-emptyDataSetView.frame.origin.y -64 ): 0;
        return -MHRealHeightValue(198)/2.0f + inset;
    }else
    {
        return -self.tableView.tableHeaderView.frame.size.height/2.0f;
    }
    
}


/// 评论的时候 滚动tableView
- (void)_scrollTheTableViewForComment{
    
    CGRect rect = CGRectZero;
    CGRect rect1 = CGRectZero;
    if (self.selectedIndexPath.row == -1) {
        /// 获取整个尾部section对应的尺寸 获取的rect是相当于tableView的尺寸
        rect = [self.tableView rectForFooterInSection:self.selectedIndexPath.section];
        /// 将尺寸转化到window的坐标系 （关键点）
        rect1 = [self.tableView convertRect:rect toViewOrWindow:nil];
    }else{
        /// 回复
        /// 获取整个尾部section对应的尺寸 获取的rect是相当于tableView的尺寸
        rect = [self.tableView rectForRowAtIndexPath:self.selectedIndexPath];
        /// 将尺寸转化到window的坐标系 （关键点）
        rect1 = [self.tableView convertRect:rect toViewOrWindow:nil];
    }
    
//    if (self.keyboardHeight > 0 ) { /// 键盘抬起 才允许滚动
//        /// 这个就是你需要滚动差值
//        CGFloat delta = self.commentToolView.mh_top - rect1.origin.y - rect1.size.height;
//        if (delta > 0) {
//            return;
//        }
//        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentOffset.y-delta) animated:NO];
//    }
    
    if (self.keyboardHeight > 0 && self.keyboardHeight != -60) { /// 键盘抬起 才允许滚动
        /// 这个就是你需要滚动差值
        CGFloat delta = self.commentToolView.mh_top - rect1.origin.y - rect1.size.height;
        if (delta > 0) {
            return;
        }
        [self.tableView setContentOffset:CGPointMake(0, self.tableView.contentOffset.y-delta) animated:NO];
    }
}


@end
